/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { ActionType, TableDropdown } from '@ant-design/pro-table';
import { PopconfirmProps, Space } from 'antd';
import React, { useMemo, useState } from 'react';
import { useTableOperateContext } from '../_utils/context';
import { isFunction } from 'lodash';
import Bar from './bar';

interface OptionsItem {
  key: string;
  name: string;
  withConfirm?: boolean;
  title?: PopconfirmProps['title'];
}
interface TableOperateProps<T> {
  data: T;
  action: ActionType;
  options: OptionsItem[] | null;
  max?: number;
}

const TableOperate = <T extends Record<string, any>>(props: TableOperateProps<T>) => {
  const [loadingMap, setLoadingMap] = useState({});
  const { onOperate } = useTableOperateContext<T>();
  const { data, action, options, max = -1 } = props;

  const [opts = [], menus = []] = useMemo(() => {
    if (!options) return [];
    if (max > 0) {
      return [options.slice(0, max), options.slice(max)];
    }
    return [options];
  }, [options]);

  const triggerOperate = (key: string, d: T) => {
    if (isFunction(onOperate)) {
      setLoadingMap((cur) => ({
        ...cur,
        [key]: true,
      }));
      onOperate(key, d)
        .then((res) => {
          if (res && res.code == 0) {
            action.reload();
          }
        })
        .finally(() => {
          setLoadingMap((cur) => ({
            ...cur,
            [key]: false,
          }));
        });
    }
  };

  const handleClick = (key: string) => triggerOperate(key, data);

  const handleSelect = (key: string) => triggerOperate(key, data);

  return (
    <Space>
      {opts.map(({ name, key, title, ...rest }) => (
        <Bar
          loading={loadingMap[key]}
          {...rest}
          key={key}
          onClick={handleClick.bind(null, key)}
          title={title || `是否确定${name}？`}
        >
          {name}
        </Bar>
      ))}
      {menus.length > 0 && (
        <TableDropdown key='actionGroup' onSelect={handleSelect} menus={menus as any} />
      )}
    </Space>
  );
};

export default TableOperate;
